from django.core.paginator import PageNotAnInteger, EmptyPage, Paginator
from django.shortcuts import render

# Create your views here.
from blog.models import Article, Catagory, Tag
from comments import models


def data_case(request):
    allcategory = Catagory.objects.all()  # 通过Category表查出所有分类
    return render(request, 'base.html',locals())


# 文章列表页
def list(request, lid):
    print(lid)
    list = Article.objects.filter(category_id=lid)  # 获取用过URL传进来的lid，然后筛选出对应的文章
    cname = Catagory.objects.get(id=lid)  # 获取当前文章的栏目名
    rname = Article.objects.filter(tui_id=2)[:6]  # 右侧热门标签
    allcategory = Catagory.objects.all()  # 导航所有分类
    hot = Article.objects.all().order_by('views')[:6]  # 通过浏览数进行排序
    tags = Tag.objects.all()  # 右侧所有文章标签
    page = request.GET.get('page')  # 在url中获取当前页数，
    paginator = Paginator(list, 5)  # 对查询到的数据对象list进行分页，设置超过5条数据就分页
    try:
        list = paginator.page(page)  # 获取当前页码的记录
    except PageNotAnInteger:
        list = paginator.page(1)  # 如果用户输入的页码不是整数时，显示第一页内容
    except EmptyPage:
        list = paginator.page(paginator.num_pages)  # 如果用户输入的页数不在系统的页码列表时，显示最后一页的内容
    return render(request, 'list.html', locals())

# 内容页
def show(request, sid):
    show = Article.objects.get(id=sid)  # 查询指定id的文章
    allcategory = Catagory.objects.all()  # 导航上的分类
    tags = Tag.objects.all()  # 右侧所有的标签
    remen = Article.objects.filter(tui_id=2)[:6]  # 右侧热门标签
    hot = Article.objects.all().order_by('?')[:3]  # 文章内容下面的您感兴趣的文章，随机推荐
    # 上一篇文章
    previous_blog = Article.objects.filter(created_time__gt=show.created_time, category=show.category.id).first()
    # 下一篇文章
    next_blog = Article.objects.filter(created_time__lt=show.created_time, category=show.category.id).last()
    show.views = show.views + 1
    show.save()
    comlist = models.Comment()
    comment_list = show.comment_set.all()
    comm_count = show.comment_set.count()
    print(comm_count)
    return render(request, 'show.html', locals())
